package com.zx.mvcframework.handle;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: myspring
 * @Package: com.zx.mvcframework.pojo
 * @ClassName: HandlerExecutionChain
 * @Author: 处理器执行链
 * @Description: 1
 * @Date: 2021/10/4 17:29
 */
public class HandlerExecutionChain {

    private final MethodHandler methodHandler;

    private final List<InterceptorHandler> interceptorList = new ArrayList<>();


    private int interceptorIndex = -1;

    public  HandlerExecutionChain(MethodHandler methodHandler ){
        this(methodHandler, Collections.emptyList());
    }

  public  HandlerExecutionChain(MethodHandler methodHandler,List<InterceptorHandler> interceptorList){
        this.methodHandler = methodHandler;
        this.interceptorList.addAll(interceptorList);
    }

    /**
     *  前置拦截
     */
   public boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        for (int i = 0; i < this.interceptorList.size(); i++) {
            InterceptorHandler interceptor = this.interceptorList.get(i);
            if (!interceptor.preHandle(request, response, this.methodHandler)) {
                triggerAfterCompletion(request, response);
                return false;
            }
            this.interceptorIndex = i;
        }
        return true;
    }


    /**
     *  拦截成功 回调函数
     */
    public void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response) {
        for (int i = this.interceptorIndex; i >= 0; i--) {
            InterceptorHandler interceptor = this.interceptorList.get(i);
            try {
                interceptor.afterCompletion(request, response, this.methodHandler);
            }
            catch (Throwable ex2) {
                System.out.println("HandlerInterceptor.afterCompletion threw exception");
            }
        }
    }

    /**
     * 后置拦截
     */
    public  void applyPostHandle(HttpServletRequest request, HttpServletResponse response )
            throws Exception {

        for (int i = this.interceptorList.size() - 1; i >= 0; i--) {
            InterceptorHandler interceptor = this.interceptorList.get(i);
            interceptor.postHandle(request, response, this.methodHandler );
        }
    }

    public MethodHandler getMethodHandler() {
        return methodHandler;
    }


}
